$(function($){
    // 获取元素
    let neirong=$('.neirong');
    let lis=$('.type li')
    let jiage=$('.jiage');
    let key=$('.key');
    let pageSize=20;
    let idx=1;
    let nav=$('.nav')
    let waibu=$('.waibu')
    // let total;
    // 一开始渲染页面的函数
     async function firstlist(idx,res,total){
        let date1=new Date().getTime();
      //判断是否传了res这个参数  
          if(!res){
              res=total=await pAjax({
                         url:`/lol/images/lol/act/img/js/heroList/hero_list.js`,
                        
                     })            
                     localStorage.setItem("data", res);
                     res=JSON.parse(localStorage.getItem('data'));
                      //  将总数据单独存放在本地存储
          localStorage.setItem("total", total);
          } 
         
                        
                      let res1;
     if(Object.prototype.toString.call(res)=="[object Object]"){
     
         res1= res.hero.filter(function(itemh,index){
                         return index>=(idx-1)*pageSize&&index<idx*pageSize
                     })
    }
      if(Object.prototype.toString.call(res)=="[object Array]"){
       res1= res.filter(function(itemh,index){
                         return index>=(idx-1)*pageSize&&index<idx*pageSize
                     })
    } 
                    render(res1);
            //  let time=console.timeEnd('test');
            //  console.log(time);
                     // 分页功能
    let pagination = document.querySelector('.pagination')
    let number;

    number=res.length;
      new Pagination(pagination, {
            pageInfo: {
                pagenum: idx,
                pagesize: pageSize,
                total: number,
                totalpage: Math.ceil(number / pageSize),
                // Math.ceil(res.total / 20)
            },
            textInfo: {
                first: '首页',
                prev: '上一页',
                next: '下一页',
                last: '末页'
            },
            // 当我们点击的时候 执行的函数
            change: function (index) {
                // index 表示当前的页数
               console.log(JSON.parse(localStorage.getItem("total")) );
                list(index)
                 scrollTo({top:400})
            }
        });
        let date2=new Date().getTime();
        let time=date2-date1;
        return time;
                 }
            let times= firstlist(idx);
    // 另一个渲染的函数
      async function list(idx,res){

                      res=JSON.parse(localStorage.getItem('data'));  
                      let res1;
     if(Object.prototype.toString.call(res)=="[object Object]"){
     
         res1= res.hero.filter(function(itemh,index){
                         return index>=(idx-1)*pageSize&&index<idx*pageSize
                     })
    }
      if(Object.prototype.toString.call(res)=="[object Array]"){
       res1= res.filter(function(itemh,index){
                         return index>=(idx-1)*pageSize&&index<idx*pageSize
                     })
    } 
                    render(res1);
                    
                     // 分页功能
    let pagination = document.querySelector('.pagination')
    let number;

    number=res.length;
      new Pagination(pagination, {
            pageInfo: {
                pagenum: idx,
                pagesize: pageSize,
                total: number,
                totalpage: Math.ceil(number / pageSize),
                // Math.ceil(res.total / 20)
            },
            textInfo: {
                first: '首页',
                prev: '上一页',
                next: '下一页',
                last: '末页'
            },
            // 当我们点击的时候 执行的函数
            change: function (index) {
                // index 表示当前的页数
          
                list(index)
                 scrollTo({top:400})
            }
        });
                 }
             
    // 详情页跳转
    neirong.on('click',function(e){
        if(e.target.classList.contains('xiang')){
            
            let id=e.target.getAttribute('idx');
            location.href='./details.html?id='+id;
            
        }
    })
    // 鼠标停留效果
    // console.log(times.PromiseResult);
  setTimeout(function(){
      let lis=$('.neirong .lis');
      let hg=lis.innerHeight()/2;
      let wg=lis.innerWidth()/2;
     
     lis.hover(function(e){
         $(e.target).append(`<span class="dian dian1"></span>`)
          $(e.target).append(`<span class="dian dian2"></span>`)
          $(e.target).append(`<span class="dian dian3"></span>`)
          $(e.target).append(`<span class="dian dian4"></span>`)
         $('.dian1').animate({
             height:hg,
         },1000,function(){
             $(e.target).append(`<span class="diandian dian5"></span>`);
             $('.dian5').animate({
                 width:wg
             },500)

         })
         $('.dian2').animate({
             height:hg,
         },1000,function(){
             $(e.target).append(`<span class="diandian dian6"></span>`);
             $('.dian6').animate({
                 width:wg
             },500)

         })
         $('.dian3').animate({
             height:hg,
         },1000,function(){
             $(e.target).append(`<span class="diandian dian7"></span>`);
             $('.dian7').animate({
                 width:wg
             },500)

         })
         $('.dian4').animate({
             height:hg,
         },1000,function(){
             $(e.target).append(`<span class="diandian dian8"></span>`);
             $('.dian8').animate({
                 width:wg
             },500)

         })
     },function(e){
        $('.dian').remove();
        $('.diandian').remove();
        // $(e.target).stop(true)
        //  $('.dian1').stop();
        //  $('.dian2').stop();
        //  $('.dian3').stop();
        //  $('.dian4').stop();
        //  $('.dian5').stop();
        //  $('.dian6').stop();
        //  $('.dian7').stop();
        //  $('.dian8').stop();
        //   $('.dian5').stop().animate({
        //          width:0
        //      },500,function(){
                
        //        $('.dian1').animate({
        //      height:0,
        //  },1000,function(){
        //       $('.dian').remove();
        //      $('.diandian').remove();
        //  })
        //  });
        //   $('.dian6').stop().animate({
        //          width:0
        //      },500,function(){
        //        $('.dian2').animate({
        //      height:0,
        //  },1000)
        //  });

        //  $('.dian7').stop().animate({
        //          width:0
        //      },500,function(){
        //        $('.dian3').animate({
        //      height:0,
        //  },1000)
        //  });
        //   $('.dian8').stop().animate({
        //          width:0
        //      },500,function(){
        //        $('.dian4').animate({
        //      height:0,
        //  },1000)
        //  });
         
     })
  
  },500)
    // 根据关键字搜索英雄
key.on('keyup',function(e){
    let val=e.target.value;
    let data=JSON.parse(localStorage.getItem('total'));
    // console.log(Object.prototype.toString.call(data));
console.log(data);
    if(Object.prototype.toString.call(data)=="[object Object]"){
        res=data.hero.filter(function(item){
        return item.keywords.indexOf(val)!=-1;
    })
    }
      if(Object.prototype.toString.call(data)=="[object Array]"){
        res=data.filter(function(item){
        return item.keywords.indexOf(val)!=-1;
    })
    }
      console.log(res);
    localStorage.setItem("data", JSON.stringify(res));
   list(idx,res);
   

})
 
    // 点击英雄类型切换数据
    lis.on('click',function(){
        let data=JSON.parse(localStorage.getItem('total'));
        this.firstElementChild.checked=true;
        if($(this).index()==0){
           firstlist(idx);
            return;
        }
        let lei=$(this).attr('class');
        res=data.hero.filter(function(item){
        return item.roles.indexOf(lei)!=-1;
    })
    console.log(res);
    localStorage.setItem('data',JSON.stringify(res))
    list(idx,res);
    })
    // 按价格排行的功能
jiage.on('click',function(e){
    let data=JSON.parse(localStorage.getItem('data'));
    console.log();
//  升序排行
    if($(e.target).hasClass('up')){
        Object.prototype.toString.call(data)=="[object Object]"? data.hero.sort(function(item,index){
            return item.goldPrice-index.goldPrice
        }):data.sort(function(item,index){
            return item.goldPrice-index.goldPrice
        });
     
       
     localStorage.setItem("data", JSON.stringify(data));
        list(idx,data)
    }
// 降序排行
     if($(e.target).hasClass('down')){
          Object.prototype.toString.call(data)=="[object Object]"? data.hero.sort(function(item,index){
            return index.goldPrice-item.goldPrice
        }):data.sort(function(item,index){
            return index.goldPrice-item.goldPrice
        });
       

        localStorage.setItem("data", JSON.stringify(data));
        list(idx,data)
    }
})
    // 切换物品页面
//   渲染数据
    nav.on('click',function(e){
        e.preventDefault();
        $(e.target).parent().addClass('active');
        $(e.target).parent().siblings().removeClass('active');
          if(e.target.classList.contains("goodthing")){
              goods();
             async function goods(){
                 let res=await pAjax({
                     url:`/lol/images/lol/act/img/js/items/items.js`
                 })
                 localStorage.setItem('goodData',res);
                 res=JSON.parse(res);
                 console.log(res);
                 waibu.html(` <ul class="wupinlan type">
                        <li class="goodType"><input type="radio" name="leixing" checked><label for="">所有物品</label></li>
                        <li class="Health"><input type="radio" name="leixing"><label for="">防御类</label></li>
                        <li class="Damage"><input type="radio" name="leixing"><label for="">攻击类</label></li>
                        <li class="SpellDamage"><input type="radio" name="leixing"><label for="">法术类</label></li>
                        <li class="Boots"><input type="radio" name="leixing"><label for="">移动速度</label></li>
                        <li class="HealthRegen"><input type="radio" name="leixing"><label for="">消耗品</label></li>
                       
                    </ul>
                    
                    <input type="text" placeholder="请输入您要搜索的物品名" class="goodkey">
                `)

                $('.pagination').remove();
               goodrender(res.items)
                // 显示物品详情页
              $('.uls li').hover(function(e){
                let symbol= $(this).attr("symbol");
                res=JSON.parse(localStorage.getItem('goodData'));
               res= res.items.filter(function(item){
                    return item.itemId==symbol;
                })[0]
                console.log(res);
               
               
                $(this).append(`<div class="detail">
                    <div><img src="${res.iconPath}"><div><h4>${res.name}</h4>
                <span>售价或合成费用${res.price}</span></div></div>
                    <div>${res.description}</div>
                </div>`)
                // 鼠标移动事件，防止出现水平滚动条
                $('.uls li').on('mousemove',function(e){
                 
                    $(".detail").css({
                        left:e.clientX-this.offsetLeft,
                        top:e.pageY-this.offsetTop+40
                    })
                 
                  
                    if(e.clientX+$(".detail").innerWidth()>innerWidth){
                         $(".detail").css({
                        left:e.clientX-this.offsetLeft-$(".detail").innerWidth()-20,
                        top:e.pageY-this.offsetTop+40
                    })
                
                    }
                })
              },function(){
                //   鼠标移出删除详情页
                $('.detail').remove()
              })
                
            //   根据关键字搜索物品
            goodkey($('.goodkey'));
             // 点击物品类型切换数据
         $('.wupinlan li').on('click',function(){
             e.stopPropagation();
        let data=JSON.parse(localStorage.getItem('goodData'));
        this.firstElementChild.checked=true;
        if($(this).index()==0){
            goodrender(data.items)
            return;
        }
         
        let lei=$(this).attr('class');
      let res=data.items.filter(function(item){
        return item.types.indexOf(lei)!=-1;
       })
      
         goodrender(res)
               // 显示物品详情页
       
 $('.uls li').hover(function(e){
    
       let data=JSON.parse(localStorage.getItem('goodData'));
       
        let lei=e.target.parentNode.getAttribute('symbol');
      let rest;
      console.log(1);
      console.log($(e.target).parent().siblings().length);
      $(e.target).siblings().length>180?rest=data:rest=data.items.filter(function(item){
        return item.itemId==lei;
       })[0];
              $(e.target).parent().append(`<div class="detail">
                    <div><img src="${rest.iconPath}"><div><h4>${rest.name}</h4>
                <span>售价或合成费用${rest.price}</span></div></div>
                    <div>${rest.description}</div>
                </div>`)
                    // 鼠标移动事件，防止出现水平滚动条
                $('.uls li').on('mousemove',function(e){
                    
                    $(".detail").css({
                        left:e.clientX-this.offsetLeft,
                        top:e.pageY-this.offsetTop+40
                    })
                    if(e.clientX+$(".detail").innerWidth()>innerWidth){
                         $(".detail").css({
                        left:e.clientX-this.offsetLeft-$(".detail").innerWidth()-20,
                        top:e.pageY-this.offsetTop+40
                    })
                    }
                })
        },function(){
                //    鼠标移出删除详情页
                $('.detail').remove()
        })
    })
        }
          }  

          if(e.target.classList.contains("hero")){
              location.reload();
          }  
    })
 
    // 物品关键字搜索函数
    function goodkey(win){
    win.on('keyup',function(e){
        let res;
    let val=e.target.value;
    let data=JSON.parse(localStorage.getItem('goodData'));
    res=data.items.filter(function(item){
        return item.keywords.indexOf(val)!=-1;
    })
    goodrender(res);
    if(res.length==0){
        neirong.html("<h3>抱歉，查找不到相关商品</h3>")
    }
      // 显示物品详情页
              $('.uls li').hover(function(e){
                let symbol= $(this).attr("symbol");
               
               res= res.filter(function(item){
                    return item.itemId==symbol;
                })[0]
                $(this).append(`<div class="detail">
                    <div><img src="${res.iconPath}"><div><h4>${res.name}</h4>
                <span>售价或合成费用${res.price}</span></div></div>
                    <div>${res.description}</div>
                </div>`)
                // 鼠标移动事件，防止出现水平滚动条
                $('.uls li').on('mousemove',function(e){
                 
                    $(".detail").css({
                        left:e.clientX-this.offsetLeft,
                        top:e.pageY-this.offsetTop+40
                    })
                    if(e.clientX+$(".detail").innerWidth()>innerWidth){
                         $(".detail").css({
                        left:e.clientX-this.offsetLeft-$(".detail").innerWidth()-20,
                        top:e.pageY-this.offsetTop+40
                    })
                    }
                })
              },function(){
                //   鼠标移出删除详情页
                $('.detail').remove()
              })
})
    }
    // 物品页内容函数
    function goodrender(res){       
     let result= res.map(function(item){        
                 return `<li symbol="${item.itemId}"><img class="open" src="${item.iconPath}"><span>${item.name}</span></li>`
                }).join("");
         neirong.html('')
 neirong.prepend(`<h3>本页面藏品较为珍贵，只展示不售卖，敬请谅解</h3>`)           
neirong.append(`<ul class="uls">${result}</ul>`)
neirong.append(`<button class="dingbu">回到顶部</button>`)
    }
    // 回到顶部功能
    
    window.onscroll=function(){
        $('.dingbu').on('click',function(){
       window.scrollTo({
            top:400,
            behavior:"smooth"
        })
    })
      
    }
    // 渲染页面的函数
    function render(result){
        neirong.html(result.map(function(item){
                    
                        return ` <div class="lis">
                    <div class="toph">
                        <span>${item.name}·${item.title}</span>
                    </div>
                    <div class="bot">
                        <img src="https://game.gtimg.cn/images/lol/act/img/skinloading/${item.heroId}004.jpg" alt="">

                        <span>￥${item.goldPrice}</span>
                        <p><button type="button" class="btn btn-primary btn-sm"><a href='./shopcar.html' style="color:white">查看购物车</a></button><button type="button"
                                class="btn btn-primary btn-sm xiang" idx="${item.heroId}">查看商品详情</button></p>
                    </div>
                </div>`
                     }))
    }
     
   
})